<?php

namespace app\adminapi\controller;

use app\model\UsersModel;
use support\Redis;
use Webman\Http\Request;

class User extends BaseAdminApi
{
    protected ?string $dataModel = UsersModel::class;
    protected array $allowSearch = ['nickname', 'username', 'email', 'phone', 'status'];

    /**
     * 不需要登录的方法
     * @var array
     */
    protected array $noNeedLogin = ['wechatLogin'];

    /**
     * 保存用户
     */
    public function saveUser(Request $request)
    {
        $params = $request->post();

        $rules = [
            'nickname' => 'required|max:50',

            'email' => 'nullable|email|max:100',
            'gender' => 'nullable|in:0,1,2',
            'birthday' => 'nullable|date',
            'status' => 'required|in:0,1'
        ];

        $messages = [
            'nickname.required' => '昵称不能为空',
            'nickname.max' => '昵称不能超过50个字符',

            'email.email' => '邮箱格式不正确',
            'email.max' => '邮箱不能超过100个字符',
            'gender.in' => '性别值只能是0、1或2',
            'birthday.date' => '生日格式不正确',
            'status.required' => '状态不能为空',
            'status.in' => '状态值只能是0或1'
        ];

        // 如果提供了用户名和密码，则验证
        if (!empty($params['username']) || !empty($params['password'])) {
            $rules['username'] = 'required|min:4|max:50';
            $rules['password'] = ['required', 'min:6', 'regex:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/'];
            $messages['username.required'] = '用户名不能为空';
            $messages['username.min'] = '用户名至少4个字符';
            $messages['username.max'] = '用户名不能超过50个字符';
            $messages['password.required'] = '密码不能为空';
            $messages['password.min'] = '密码至少6个字符';
            $messages['password.regex'] = '密码必须包含字母、数字和特殊字符';
        }

        // 编辑时密码可选
        if (isset($params['id']) && !empty($params['id']) && !empty($params['password'])) {
            $rules['password'] = ['min:6', 'regex:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/'];
            $messages['password.min'] = '密码至少6个字符';
            $messages['password.regex'] = '密码必须包含字母、数字和特殊字符';
        }

        $validator = validator($params, $rules, $messages);

        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }

        try {
            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑用户
                $user = UsersModel::find($params['id']);
                if (!$user) {
                    return $this->fail('用户不存在');
                }

                // 检查用户名是否重复（排除自己）
                if (!empty($params['username'])) {
                    $existUser = UsersModel::where('username', $params['username'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existUser) {
                        return $this->fail('用户名已存在');
                    }
                }



                // 检查邮箱是否重复（排除自己）
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existEmail) {
                        return $this->fail('邮箱已存在');
                    }
                }

                $updateData = [
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status']
                ];

                // 如果提供了用户名，则更新
                if (!empty($params['username'])) {
                    $updateData['username'] = $params['username'];
                    $updateData['login_type'] = 'username';
                }

                // 如果提供了新密码，则更新密码
                if (!empty($params['password'])) {
                    $updateData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }

                $user->update($updateData);

                return $this->success('用户更新成功');
            } else {
                // 新增用户
                $userData = [
                    'id' => randomString(),
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status'],
                    'login_type' => 'username'
                ];

                // 如果提供了用户名和密码
                if (!empty($params['username']) && !empty($params['password'])) {
                    // 检查用户名是否重复
                    $existUser = UsersModel::where('username', $params['username'])->first();
                    if ($existUser) {
                        return $this->fail('用户名已存在');
                    }
                    
                    $userData['username'] = $params['username'];
                    $userData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }



                // 检查邮箱是否重复
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])->first();
                    if ($existEmail) {
                        return $this->fail('邮箱已存在');
                    }
                }

                UsersModel::create($userData);

                return $this->success('用户创建成功');
            }
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 删除用户
     */
    public function deleteUser(Request $request)
    {
        $params = $request->post();

        if (!isset($params['id']) || empty($params['id'])) {
            return $this->fail('请提供要删除的用户ID');
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return $this->fail('用户不存在');
            }

            // 删除用户
            $user->delete();

            return $this->success('用户删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 禁用/启用用户
     */
    public function toggleUserStatus(Request $request)
    {
        $params = $request->post();

        if (!isset($params['id']) || empty($params['id'])) {
            return $this->fail('请提供用户ID');
        }

        if (!isset($params['status']) || !in_array($params['status'], [0, 1])) {
            return $this->fail('状态值只能是0或1');
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return $this->fail('用户不存在');
            }

            $user->update(['status' => $params['status']]);

            $statusText = $params['status'] == 1 ? '启用' : '禁用';
            return $this->success('用户' . $statusText . '成功');
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(Request $request)
    {
        $token = $request->header('authorization');
        
        if (!$token) {
            return $this->fail('请先登录', 401);
        }

        $userId = Redis::get($token);
        
        if (!$userId) {
            return $this->fail('登录已过期', 401);
        }

        $user = UsersModel::find($userId);
        
        if (!$user) {
            return $this->fail('用户不存在', 401);
        }

        return $this->success($user);
    }
}